package com.zhike.utils;


import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @Author: zhike
 * @CreateTime: 2024/5/3
 * @Description:
 */
public class EmailUtils {
    public static void sendEmail(String vin) {

        // 设置SMTP服务器地址和端口
        String host = "smtp.mxhichina.com"; // 阿里邮箱SMTP服务器地址
        String port = "25"; // 阿里邮箱SMTP端口，有时可能需要使用465或587端口，并使用SSL或TLS加密

        // 发件人邮箱账号和密码
        String from = "wangbiao@deepexi.com";
        String password = "Wb159248@";

        // 收件人邮箱账号
        String to = "wangbiao@deepexi.com";

        // 邮件主题和正文
        String subject = "车辆告警";
        String body = vin+":车辆电池温度过高！！！！！";

        // 设置邮件会话属性
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
//            props.put("mail.smtp.starttls.enable", "true"); // 如果使用TLS加密，则启用此行
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);

        // 获取默认session对象
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(from, password);
                    }
                });

        try {

            // 创建默认的 MimeMessage 对象
            Message message = new MimeMessage(session);

            // 设置 From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // 设置 To: 头部头字段
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to));

            // 设置 Subject: 头部头字段
            message.setSubject(subject);

            // 设置消息体
            message.setText(body);

            // 发送消息
            Transport.send(message);

//            System.out.println("Sent message successfully....");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
